import { Component, OnInit, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { NzFormatEmitEvent, NzTreeNodeOptions } from 'ng-zorro-antd';
import { DataDictionaryService } from 'services';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
    moduleId: module.id,
    selector: 'data-tree-select',
    templateUrl: 'data-tree-select.component.html',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => DataTreeSelectComponent),
            multi: true
        },
        DataDictionaryService
    ]
})
export class DataTreeSelectComponent implements ControlValueAccessor, OnInit {
    @Input() width = '100%';
    _groupCode: string;
    @Input()
    set groupCode(group: any) {
        this._groupCode = group;
        this.getTreeNode();

    }
    get groupCode(): any { return this._groupCode; }

    selectCode: string;
    @Input() islocation = false;// true 是位置树
    @Output() selectTreechange = new EventEmitter<string>();
    dataTrees: NzTreeNodeOptions[] = [];
    onChangeListener; // 改变值回调
    onTouchedListener; // 交互回调
    isDisabled: boolean;
    //selectedKeys = [];
    constructor(private dictionaryService: DataDictionaryService) {
    }

    writeValue(obj: any): void {
        this.selectCode = obj;
        //this.selectedKeys = [this.selectCode];
    }

    registerOnChange(fn: any): void {
        this.onChangeListener = fn; // 保存这个函数
    }

    registerOnTouched(fn: any): void {
        this.onTouchedListener = fn; // 保存这个函数
    }

    setDisabledState?(isDisabled: boolean): void {
        this.isDisabled = isDisabled;
    }

    ngOnInit(): void {

    }

    getTreeNode() {
        if (this.islocation) {
            this.dictionaryService.getlocationpNzTree().subscribe(result => {
                this.dataTrees = result;
            });

        } else {
            this.dictionaryService.getDataGroupNzTree(this.groupCode, this.selectCode).subscribe(result => {
                this.dataTrees = result;
            });
        }

    }

    onChange(key: string) {
        this.selectCode = key;
        //this.selectedKeys = [this.selectCode];
        this.selectTreechange.emit(key);
        if (this.onChangeListener) {
            this.onChangeListener(key); // 告诉form，你的表单值改变成了
        }

        if (this.onTouchedListener) {
            this.onTouchedListener(); // 告诉form，你的表单有交互发生
        }
    }
}
